<template>
    <div>
        <div>
            <van-search v-model="searchValue" shape="round" placeholder="请输入搜索关键词"/>
            <div class="search_wrap" v-if="resultList.length === 0">
                <p class="hot_title">热门搜索</p>
                <ul class="hot_name_wrap">
                    <li class="hot_item" v-for="( obj, index) in hotSearch" :key="index" @click="btn(obj.first)">
                        {{ obj.first }}
                    </li>
                </ul>
            </div>
          <div class="search_wrap" v-else>
            <p class="hot_title">最佳匹配</p>
            <SongItem v-for="(obj,index) in resultList" :key="obj.id" :name="obj.name" :author="obj.ar[0].name"
                      :id="index" @click="updateIndex(obj)"/>

          </div>
        </div>
    </div>
</template>

<script>
import {mapMutations} from 'vuex';
import SongItem from '@/components/SongItem.vue';
import { hotSearchNameAPI, searchResultAPI } from '@/api'
export default {
    components: { SongItem },
    data() {
        return {
          searchValue: '',
          hotSearch: [],
          resultList: [],
          timer: '',
          searchKey: '',

        };
    },
    methods: {
      ...mapMutations(['updatePlayList', 'updatePlayListIndex', 'play']),
      async btn(srt) {
        this.searchValue = srt;
        const res = await searchResultAPI({keywords: this.searchValue});
        this.resultList = res.data.result.songs;
        console.log('歌曲列表', this.resultList);

      },
      async updateIndex(item) {
        item.al.name = item.name;
        item.al.id = item.id;
        console.log(item.name, item.id);
        await this.$store.commit('pushPlayList', item);
        await this.$store.commit('updatePlayListIndex', this.$store.state.playList.length - 1);
        await this.play();
      },
    },
    async created() {
        const qwe = await hotSearchNameAPI()

        this.hotSearch = qwe.data.result.hots
    },
    watch: {
        searchValue(val) {
            clearTimeout(this.timer)
            if (val.length === 0) {
                return this.resultList = [];
            }
            this.timer = setTimeout(async () => {
              const res = await searchResultAPI({keywords: val});

                this.resultList = res.data.result.songs;
              console.log(this.resultList);
            }, 500);

        }
    }

};
</script>
<style scoped>


.hot_title {
    font-size: 0.32rem;
    color: #666;
}

.hot_name_wrap {
    margin: 0.266667rem;
}

.hot_item {
    display: inline-block;
    height: 0.853333rem;
    margin-right: 0.213333rem;
    margin-bottom: 0.213333rem;
    padding: 0 0.373333rem;
    font-size: 0.373333rem;
    line-height: 0.853333rem;
    color: #333;

  border-radius: 0.853333rem;
    border: 1px solid #d3d4da;
}


</style>